package config;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by je on 2015/7/6.
 */
public class GameConfig {

    private int width ;
    private int height ;
    private int padding ;
    private int size ;
    private String title ;

    public String getTitle() {
        return title;
    }

    private List<LayerConfig> layerConfigs = new ArrayList<LayerConfig>() ;

    private GameConfig() throws DocumentException {
        SAXReader reader = new SAXReader();
        Document document = reader.read(GameConfig.class.getResource("/config/cfg.xml"));
        Element rootElement = document.getRootElement();

        setFrameConfig(rootElement.element("frame"));
        setSystemConfig(rootElement.element("system"));
        setDataConfig(rootElement.element("data"));
    }

    private static GameConfig gameConfig ;

    public static GameConfig getInstance(){
        if (gameConfig == null){
            try {
                gameConfig = new GameConfig();
            } catch (DocumentException e) {
                throw new RuntimeException("读取xml出错",e);
            }
        }
        return gameConfig;
    }

    private void setFrameConfig(Element frame) {
        this.width = Integer.valueOf(frame.attributeValue("width"));
        this.height = Integer.valueOf(frame.attributeValue("height"));
        this.padding = Integer.valueOf(frame.attributeValue("padding"));
        this.size = Integer.valueOf(frame.attributeValue("size"));
        this.title = frame.attributeValue("title");
        List<Element> layers = frame.elements("layer");
        LayerConfig layerConfig;
        for (Element layer : layers) {
            layerConfig = new LayerConfig();
            layerConfig.setClassName(layer.attributeValue("class"));
            layerConfig.setX(Integer.valueOf(layer.attributeValue("x")));
            layerConfig.setY(Integer.valueOf(layer.attributeValue("y")));
            layerConfig.setW(Integer.valueOf(layer.attributeValue("w")));
            layerConfig.setH(Integer.valueOf(layer.attributeValue("h")));
            layerConfigs.add(layerConfig);
        }
    }

    private void setSystemConfig(Element system){

    }

    private void setDataConfig(Element data){

    }

    @Override
    public String toString() {
        return "GameConfig{" +
                "width=" + width +
                ", height=" + height +
                ", padding=" + padding +
                ", size=" + size +
                ", layerConfigs=" + layerConfigs +
                '}';
    }


    public int getWidth() {
        return width;
    }

    public int getHeight() {
        return height;
    }

    public int getPadding() {
        return padding;
    }

    public int getSize() {
        return size;
    }

    public List<LayerConfig> getLayerConfigs() {
        return layerConfigs;
    }
}
